//
//  StatusListViewController.swift
//  JLWeibo
//
//  Created by sunjinliang on 15/12/10.
//  Copyright © 2015年 sunjinliang. All rights reserved.
//

import UIKit
import SDWebImage
class StatusListViewController {
     
     lazy var statusList = [StatusViewModel]()
    /// 加载微博数据
    ///
    /// - parameter finished: 返回是否下载成功
    func loadUserStatus(isPullup isPullup:Bool, finished:(isSuccessed:Bool)->()){
         let since_id =  !isPullup ? (statusList.first?.status.id ?? 0) : 0
        let max_id = isPullup ?  (statusList.last?.status.id ?? 0): 0
        StatusDAL.loadStatus(since_id, max_id: max_id) { (array) -> () in
            guard let array = array else{
                finished(isSuccessed: false)
                return
            }
            var dictList = [StatusViewModel]()
            for dict1 in array {
                dictList.append(StatusViewModel(statusM: Status(dict: dict1)))
            }
//            print("加载了\(dictList.count)条数据")
            if since_id > 0 {
                self.statusList  = dictList + self.statusList
            }else{
                self.statusList += dictList
            }

             self.cacheSingleImage(self.statusList, finished: finished)
        }
    }
    /// 缓存单张图片
    ///
    /// - parameter statusList: 传入模型数组
    /// - parameter finished:   缓存完成回调
    func cacheSingleImage(statusList: [StatusViewModel],finished:(isSuccessed:Bool)->()){
        
        
        let group = dispatch_group_create()
        for vm in statusList {
            if vm.thumbnailArray?.count != 1{
                continue
            }
           
            SDWebImageManager.sharedManager().downloadImageWithURL(vm.thumbnailArray![0], options: [SDWebImageOptions.RetryFailed,SDWebImageOptions.RefreshCached], progress: nil, completed: { (image, _, _, _, _) -> Void in
                dispatch_group_enter(group)
                dispatch_group_leave(group)
//                print(image)
            })
            
        }
        
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            finished(isSuccessed: true)
        }
        
        
        
    }
}
 